package cn.jjxx.modules.dj.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.framework.customutil.sms.MapToBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.baomidou.mybatisplus.annotations.TableName;
import com.baomidou.mybatisplus.mapper.Wrapper;

import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.common.entity.tree.BootstrapTreeHelper;
import cn.jjxx.core.common.entity.tree.BootstrapTreeNode;
import cn.jjxx.core.common.entity.tree.TreeSortUtil;
import cn.jjxx.core.config.BillConfig;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.QueryPropertyPreFilter;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import cn.jjxx.core.utils.MapBeanUtil;
import cn.jjxx.core.utils.MessageUtils;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import cn.jjxx.modules.dj.entity.DjOrg;
import cn.jjxx.modules.dj.service.IDjOrgService;
import cn.jjxx.modules.map.service.ICommonMapService;
import cn.jjxx.modules.pb.entity.PbAge;
import cn.jjxx.modules.pb.entity.PbEducation;
import cn.jjxx.modules.pb.entity.PbSexRate;
import cn.jjxx.modules.pb.service.IPbAgeService;
import cn.jjxx.modules.pb.service.IPbEducationService;
import cn.jjxx.modules.pb.service.IPbSexRateService;
import cn.jjxx.modules.record.entity.DevelopmentOfMembers;
import cn.jjxx.modules.record.service.IDevelopmentOfMembersService;
import cn.jjxx.modules.sys.entity.Attachment;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.service.IAttachmentService;
import cn.jjxx.modules.sys.utils.UserUtils;

/**   
 * @Title: 党组织管理
 * @Description: 党组织管理
 * @author yw
 * @date 2022-01-11 17:20:00
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/dj/djorg")
@RequiresPathPermission("dj:djorg")
public class DjOrgController extends BaseBeanController<DjOrg> {

    @Autowired
    protected IDjOrgService djOrgService;
    @Autowired
    protected ICommonMapService commonMapService;

    public DjOrg get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return djOrgService.selectById(id);
        } else {
            return newModel();
        }
    }

	/**
	 * @Description: 根据获取党组织管理的实体数据 .<br>
	 * @param id 主键Id.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

	/**
	 * @Description: 根据查询条件动态加载党组织管理的树数据 .<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
	@ResponseBody
	@RequestMapping(value = "treeData")
	public void treeData(Queryable queryable,
			@RequestParam(value = "nodeid", required = false, defaultValue = "") String nodeid,
			@RequestParam(value = "async", required = false, defaultValue = "false") boolean async,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		EntityWrapper<DjOrg> entityWrapper = new EntityWrapper<DjOrg>(entityClass);
		entityWrapper.setTableAlias("t.");
		List<DjOrg> treeNodeList = null;
		if (!async) { // 非异步 查自己和子子孙孙
			treeNodeList = djOrgService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sort(treeNodeList).async(treeNodeList);
		} else { // 异步模式只查自己
			// queryable.addCondition("parentId", nodeid);
			if (ObjectUtils.isNullOrEmpty(nodeid)) {
				// 判断的应该是多个OR条件
				entityWrapper.isNull("parentId");
			} else {
				entityWrapper.eq("parentId", nodeid);
			}
			treeNodeList = djOrgService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sync(treeNodeList);
		}
		PropertyPreFilterable propertyPreFilterable = new QueryPropertyPreFilter();
		propertyPreFilterable.addQueryProperty("id", "name", "expanded", "hasChildren", "leaf", "loaded", "level",
				"parentId");
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
		PageJson<DjOrg> pagejson = new PageJson<DjOrg>(treeNodeList);
		String content = JSON.toJSONString(pagejson, filter);
		StringUtils.printJson(response, content);
	}

	/**
	 * @Description: 根据页码和每页记录数，以及查询条件动态加载党组织管理的数据 .<br>
	 * @param nodeid 节点Id.<br>
	 * @param async 是否异步.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
	@RequestMapping(value = "ajaxTreeList", method ={ RequestMethod.GET, RequestMethod.POST })
	private void ajaxTreeList(Queryable queryable,
			@RequestParam(value = "nodeid", required = false, defaultValue = "") String nodeid,
			@RequestParam(value = "async", required = false, defaultValue = "false") boolean async,
			HttpServletRequest request, HttpServletResponse response, PropertyPreFilterable propertyPreFilterable)
			throws IOException {
		EntityWrapper<DjOrg> entityWrapper = new EntityWrapper<DjOrg>(entityClass);
		entityWrapper.setTableAlias("t.");
		List<DjOrg> treeNodeList = null;
		if (!async) { // 非异步 查自己和子子孙孙
			treeNodeList = djOrgService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sort(treeNodeList).async(treeNodeList);
		} else { // 异步模式只查自己
			// queryable.addCondition("parentId", nodeid);
			if (ObjectUtils.isNullOrEmpty(nodeid)) {
				// 判断的应该是多个OR条件
				entityWrapper.isNull("parentId");
			} else {
				entityWrapper.eq("parentId", nodeid);
			}
			treeNodeList = djOrgService.selectTreeList(queryable, entityWrapper);
			TreeSortUtil.create().sync(treeNodeList);
		}
		propertyPreFilterable.addQueryProperty("id", "expanded", "hasChildren", "leaf", "loaded", "level", "parentId");
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
		PageJson<DjOrg> pagejson = new PageJson<DjOrg>(treeNodeList);
		String content = JSON.toJSONString(pagejson, filter);
		StringUtils.printJson(response, content);
	}

	/**
	 * @Description: 根据查询条件动态加载党组织管理的适合于bootstrapTree的数据 .<br>
	 * @param nodeid 节点Id.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
	@RequestMapping(value = "bootstrapTreeData")
	private void bootstrapTreeData(Queryable queryable,
			@RequestParam(value = "nodeid", required = false, defaultValue = "") String nodeid, HttpServletRequest request,
			HttpServletResponse response, PropertyPreFilterable propertyPreFilterable) throws IOException {
		EntityWrapper<DjOrg> entityWrapper = new EntityWrapper<DjOrg>(entityClass);
		entityWrapper.setTableAlias("t.");
		List<DjOrg> treeNodeList = djOrgService.selectTreeList(queryable, entityWrapper);
		List<BootstrapTreeNode> bootstrapTreeNodes = BootstrapTreeHelper.create().sort(treeNodeList);
		propertyPreFilterable.addQueryProperty("text", "href", "tags", "nodes");
		SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
		String content = JSON.toJSONString(bootstrapTreeNodes, filter);
		StringUtils.printJson(response, content);
	}

	/**
	 * @Description: 跳转至党组织管理的添加界面 .<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        if (!model.containsAttribute("data")) {
            model.addAttribute("data", newModel());
        }
        return display("edit");
    }
    
	/**
	 * @Description: 新增党组织管理的数据 .<br>
	 * @param djOrg 党组织管理实体类.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") DjOrg djOrg, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(djOrg, request, response, result);
    }

	/**
	 * @Description: 跳转至党组织管理的更新界面 .<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        DjOrg djOrg = get(id);
        model.addAttribute("data", djOrg);
        return display("edit");
    }

	/**
	 * @Description: 修改党组织管理的数据 .<br>
	 * @param djOrg 党组织管理实体类.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") DjOrg djOrg, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(djOrg, request, response, result);
    }

	/**
	 * @Description: 执行保存党组织管理的数据操作 .<br>
	 * @param djOrg 党组织管理实体类.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(DjOrg djOrg, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("保存成功");
        if (hasError(djOrg, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(djOrg.getId())) {
                djOrgService.insert(djOrg);
            } else {
                djOrgService.insertOrUpdate(djOrg);
            }
            ajaxJson.setData(djOrg);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

	/**
	 * @Description: 单条删除党组织管理 .<br>
	 * @param id 单据Id.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        TableName table = DjOrg.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
        	List<String> ids = Arrays.asList(id.split(","));
        	//得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, ids);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("删除失败,"+quoteMsg);
				return ajaxJson;
			}
            djOrgService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 执行保存党组织管理的数据操作 .<br>
	 * @param ids 单据Id集合.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("批量删除成功");
        TableName table = DjOrg.class.getAnnotation(TableName.class);
    	String tableName = table.value();
		String dbName = MessageUtils.getMessage("connection.dbname");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            //得到被其他表引用的结果
			String quoteMsg = commonMapService.quoteMsg(dbName, tableName, idList);
			if(StringUtils.isNotEmpty(quoteMsg)){
				ajaxJson.setMsg("批量删除失败,"+quoteMsg);
				return ajaxJson;
			}
            djOrgService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("批量删除失败");
        }
        return ajaxJson;
    }

	/**
	 * @Description: 跳转至党组织管理的查看界面 .<br>
	 * @param ids 单据Id.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        DjOrg djOrg = get(id);
        model.addAttribute("data", djOrg);
        return display("edit");
    }

	/**
	 * @Description: 验证党组织管理功能数据的唯一性 .<br>
	 * @param duplicateValid 校验实体类.<br>
	 * @author yw .<br>
	 * @date 2022-01-11 17:20:00.<br>
	 */
    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<DjOrg> entityWrapper = new EntityWrapper<DjOrg>(entityClass);
            valid = djOrgService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }
    
    
    
    
    
    
    
    
    
    /**
     * @Description: 得到可以被审核的单据 .<br>
     * @param bills 单据Id集合.<br>
     * @param status 可操作状态.<br>
     * @author yw .<br>
     * @date 2022-01-11 17:20:00 .<br>
     */
    private List<String> getAllowOptBills(List<String> bills,String status){
    	EntityWrapper<DjOrg> wrapper = new EntityWrapper<DjOrg>();
    	wrapper.in("id", bills);
    	wrapper.eq("status", status);
    	List<DjOrg> list = djOrgService.selectList(wrapper);
    	bills = new ArrayList<String>();
    	for(DjOrg bean:list){
    		bills.add(bean.getId());
    	}
    	return bills;
    }
    
    /**
     * @Description: 设置批量更新参数 .<br>
     * @param bills 可以操作的Id集合.<br>
     * @param newStatus 被修改的状态设置值.<br>
     * @author yw .<br>
     * @date 2022-01-11 17:20:00 .<br>
     */
    private List<DjOrg> setBacthUpdate(List<String> bills,String newStatus){
    	List<DjOrg> list = new ArrayList<DjOrg>();
    	User user = UserUtils.getUser();
    	if(bills.size()>0){
    		list = djOrgService.selectBatchIds(bills);
        	for(DjOrg bean:list){
        		bean.setStatus(Integer.valueOf(newStatus));
        		if(newStatus.equals(String.valueOf(BillConfig.SAVE))||
        				newStatus.equals(String.valueOf(BillConfig.SUBMIT))){
        		}
        	}
    	}
    	return list;
    }
    
    
    /**党组织数
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getOrgNum", method = { RequestMethod.GET, RequestMethod.POST })
    private AjaxJson getOrgNum(HttpServletRequest request, HttpServletResponse response) throws IOException {
        
        List<Map<String,Object>> list = djOrgService.selectOrgNum();
        AjaxJson aj = new AjaxJson();
        aj.setData(list);
        return aj;
    }
    
    @Autowired
    protected IPbAgeService pbAgeService;
    @Autowired
    protected IPbSexRateService pbSexRateService;
    @Autowired
    protected IPbEducationService pbEducationService;
    @Autowired
    protected IDevelopmentOfMembersService developmentOfMembersService;

    @ResponseBody
    @RequestMapping(value = "getOrgPeopleNum", method = { RequestMethod.GET, RequestMethod.POST })
    private AjaxJson getOrgPeopleNum(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Map<String, Object> mapData= new HashMap<>();

    	EntityWrapper<DevelopmentOfMembers> wrapperDevelopmentOfMembers = new EntityWrapper<>();        
        List<DevelopmentOfMembers> listDevelopmentOfMembers = developmentOfMembersService.selectList(wrapperDevelopmentOfMembers);
        mapData.put("listDevelopmentOfMembers", listDevelopmentOfMembers);
        
    	EntityWrapper<PbAge> wrapperAge = new EntityWrapper<>();        
        List<PbAge> listAge = pbAgeService.selectList(wrapperAge);
        mapData.put("listAge", listAge);        

    	EntityWrapper<PbSexRate> wrapperSex = new EntityWrapper<>();        
        List<PbSexRate> listPbSexRate = pbSexRateService.selectList(wrapperSex);
        mapData.put("listPbSexRate", listPbSexRate);
        
    	EntityWrapper<PbEducation> wrapperPbEducation = new EntityWrapper<>();        
        List<PbEducation> listPbEducation = pbEducationService.selectList(wrapperPbEducation);
        mapData.put("listPbEducation", listPbEducation);
        
        AjaxJson aj = new AjaxJson();
        aj.setData(mapData);
        return aj;
    }
    

	@Autowired
	private IAttachmentService attachmentService;


	private void getAttachments(List<DjOrg> list) {
		List<String> ids =new ArrayList<>();
		for (DjOrg pp : list) {
			ids.add(pp.getId());
		}
		Wrapper<Attachment> wrapper=new EntityWrapper<>();
		wrapper.in("bill_id", ids);
		List<Attachment> atsAttachments = attachmentService.selectList(wrapper);
		for (DjOrg pp : list) {
			for (Attachment attachment : atsAttachments) {
				if(pp.getId().equals(attachment.getBillId())) {
					if(null == pp.getAttachments()) {
						List<String> listAts = new ArrayList<String>();
						pp.setAttachments(listAts);
					}
					pp.getAttachments().add(attachment.getFilepath());
				}
			}
		}
	}

	
    /**获取党建品牌信息
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "getPartyBrand", method = { RequestMethod.GET, RequestMethod.POST })
    private AjaxJson getPartyBrand(HttpServletRequest request, HttpServletResponse response) throws IOException {

        EntityWrapper<DjOrg> wrapperOrg = new EntityWrapper<DjOrg>();
        wrapperOrg.eq("org_type", "3");
        List<DjOrg> listDjOrg = djOrgService.selectList(wrapperOrg);
        getAttachments(listDjOrg);
        List<Map> filedList = MapBeanUtil.listByFilter(listDjOrg, "id,brandName,remarks,attachments");
        AjaxJson aj = new AjaxJson();
        aj.setData(filedList);
        return aj;
    }
}
